define(['angularAMD','moment'], function (angularAMD,moment) {
    angularAMD.service('B0205Service', ['$rootScope', '$filter', '$translate', 'config', 'MMWService', '$mdDialog', '$calculater', '$timeout', '$mddProvider',
        function($rootScope, $filter, $translate, config, $MMWService, $mdDialog, $calculater, $timeout, $mddProvider){
            var service = this, machine_no,plotInfo = {}; // plot.info.get
            var nowdatetime = $filter('date')(new Date(), 'yyyy/MM/dd HH:mm:ss');
            var feedingOpionOn = (config.cache.sys_parameter.MaterialFeedingOption == '1'); //系統上料叫料開關
            service.init = function(machine,plot,type, feedback){

                var mode ='trackIn';

                var insertdata = {};
                var plotCheckInfo = [];

                var production_inf_detail_backup = []; //生產資訊收集
                //20210519 Modify by德義家興for#90580
                var op_plugin = false;

                if(type=='line'){
                    machine_no = machine.area_no;
                }else{
                    machine_no = machine.machine_no;
                }

                //20220301 add by 翰鴻 for M#102396
                var plotCollectInfo = [];
                var plugin = '';
                //開啟進站視窗
                function openDialog(plotInfo, waitReasonList, opPlugInDetail){
                    $mddProvider.UseForm('B0205', () =>{
                        $mdDialog.dialog(
                            'module/moduleB/program/B02/B0205/B0205.html',
                            function (dialog) {
                                let _hide = dialog.hide;
                                dialog.op_plug_in = plot.op_plug_in;
                                dialog.plotInfo =  plotInfo
                                return {                                
                                    css_url:'module/moduleB/program/B02/B0205/B0205.css',
                                    mode: mode,
                                    plotInfo: plotInfo,
                                    machine_no : machine_no,
                                    open_scan_column : plot.open_scan_column,
                                    searchWaitReason: '',
                                    waitReasonTime: (waitReasonList&&waitReasonList.length >0)? waitReasonList[0].reason_time : '',
                                    waitReasonList: waitReasonList,
                                    waitReasonListCopy: [],
                                    scan_func_val:'',
                                    LeanModule: (config.cache.sys_parameter['LeanModule'] == 1),
                                    IsInjectionMolding: (config.cache.sys_parameter.IsInjectionMolding == '1' || config.cache.sys_parameter.IsInjectionMolding == 'Y' ||
                                    config.cache.sys_parameter.ISINJECTIONMOLDING == '1' ||
                                    config.cache.sys_parameter.ISINJECTIONMOLDING == 'Y'), // 注塑模組
                                    op_plug_in: plot.op_plug_in, // 是否有爐批號 → 0(無) ; 1(有)
                                    heat_plot_no: opPlugInDetail.heat_plot_no || '', // 爐批號
                                    FasteningPackage: config.cache.sys_parameter.FasteningPackage, // 紧固件行业包 → 0(關閉) ; 1(開啟)
                                    //20210519 Modify by德義家興for#90580
                                    isPlugInEqualFive: op_plugin, //序列號收集按鈕是否顯示
                                    PCSNoList:[], //序列號收集grid
                                    PCSNoList_count: 0, //grid的筆數
                                    NCType: false,
                                    NCName: '',
                                    hiddenFileName: '',
                                    hiddenFileVersion: '',
                                    //20220301 add by 翰鴻 for M#102396
                                    plotSaveCollectInfo: [],
                                    plotCheckInfo: plotCheckInfo, //生產資訊收集验证
                                    backToTrackIn: backToTrackIn,//返回进站報工畫面                                
                                    plugin: plugin,
                                    plotCollectInfo: plotCollectInfo,
                                    //20220602 add by 翰鴻 for M#112917
                                    FilePath: '',
                                    _event: {
                                         // 20230411 add by shiwl for M#0132161
                                        'B0205_wait': {
                                                isShown: dialog.LeanModule ? 'Y' : 'N'
                                         },
                                         'B0205_waitReasonTime': {
                                            isShown: dialog.LeanModule ? 'Y' : 'N'
                                        },
                                        'B0205_datetime': {
                                            displayText: plot.op_plug_in == '1' ? $filter('translate')('B0205.heat_plot_no'):'',
                                        },
                                        'B0205_vehicle_no': {// 開窗選擇載具編號
                                            isShown: config.cache.sys_parameter.FasteningPackage == '1' || config.cache.sys_parameter.FasteningPackage == 'Y' ? 'Y' : 'N',
                                            click: () => {
                                                $rootScope.showQueryList({
                                                    header: [
                                                        { label: $filter('translate')('B0206.trackOut.vehicle_no'), code: 'vehicle_no' },
                                                        { label: $filter('translate')('B0206.trackOut.vehicle_name'), code: 'vehicle_name' },
                                                        { label: $filter('translate')('B0206.trackOut.vehicle_weight'), code: 'vehicle_weight' },
                                                        { label: $filter('translate')('B0206.trackOut.vehicle_capacity'), code: 'vehicle_capacity' }
                                                    ],
                                                    query: function (conditions, feedback) {
                                                        vehicle_no_info_get('', feedback);
                                                    },
                                                    selectCode: dialog.plotInfo.fastening_info_detail.vehicle_no,
                                                    confirm: function (selectItem, query_dialog) {
                                                        dialog.plotInfo.fastening_info_detail.vehicle_no = selectItem.vehicle_no;
                                                        dialog.plotInfo.fastening_info_detail.vehicle_name = selectItem.vehicle_name;
                                                        dialog.plotInfo.fastening_info_detail.vehicle_weight = selectItem.vehicle_weight;
                                                        dialog.plotInfo.fastening_info_detail.vehicle_capacity = selectItem.vehicle_capacity;
                                                        dialog.plotInfo.fastening_info_detail.double_unit_qty = undefined; // 有載具編號的情況，雙單位計算公式會不同，所以刷新載具編號時，也要重新輸入雙單位數量
                                                        query_dialog.hide();
                                                    }
                                                });
                                            }

                                        },
                                        'B0205_heat_plot_no':{
                                            isShown: (dialog.op_plug_in == '1') ? 'Y' : 'N'
                                        },
                                        'B0205_NCCode': {
                                            click: () => {
                                                $rootScope.showQueryList({
                                                    header: [
                                                        { label: $filter('translate')('B0205.NC_DDL.LotNo'), code: 'lotNO' },
                                                        { label: $filter('translate')('B0205.NC_DDL.ProductNo'), code: 'ProductNO' },
                                                        { label: $filter('translate')('B0205.NC_DDL.ProductVersion'), code: 'ProductVersion' },
                                                        { label: $filter('translate')('B0205.NC_DDL.OPNO'), code: 'OPNo' },
                                                        { label: $filter('translate')('B0205.NC_DDL.EquipmentNo'), code: 'EquipmentNO' },
                                                        { label: $filter('translate')('B0205.NC_DDL.FileName'), code: 'FileName' },
                                                        { label: $filter('translate')('B0205.NC_DDL.FileVersion'), code: 'FileVersion' }
                                                    ],
                                                    query: function (conditions, feedback) {
                                                        //vehicle_no_info_get('', feedback);
                                                        NCCode_info_get(feedback, dialog.plotInfo.plot_no, dialog.plotInfo.op_no, machine_no);
                                                    },
                                                    confirm: function (selectItem, query_dialog) {
                                                        //20220607 modify by 翰鴻 for M#112917
                                                        dialog.NCCode = DeleteEX(selectItem.FileName) + '-' + selectItem.FileVersion + GetEX(selectItem.FileName);
                                                        //隱藏欄位
                                                        dialog.hiddenFileName = selectItem.FileName;
                                                        dialog.hiddenFileVersion = selectItem.FileVersion;
                                                        //20220602 add by 翰鴻 for M#112917
                                                        var serverAddress = 'http://' + config.server.ip + ':' + config.server.port + '/';
                                                        // 20230818 modify by wenwei for M#142322 NC代码档案下载错误
                                                        dialog.FilePath = `${serverAddress}${config.server.name}/ncFiles/${selectItem.ProductNO}_${selectItem.ProductVersion}/${selectItem.OPNo}/${selectItem.EquipmentNO}/${selectItem.DocFileName}`;
                                                        query_dialog.hide();
                                                    }
                                                });
                                            }
                                        },
                                        'B0205_NCName': {
                                            isDisabled:'Y'
                                        },
                                        'B0205_denominator': {
                                            isShown: config.cache.sys_parameter.FasteningPackage == '1' || config.cache.sys_parameter.FasteningPackage == 'Y' ? 'Y' : 'N',
                                        },
                                        'B0205_wait_reason_searchWaitReason': {
                                            click: () => {
                                                $rootScope.showQueryList({
                                                    key: 'reason_no',
                                                    header: [
                                                        { label: $filter('translate')('B0205.leanModule.list.reason_no'), code: 'reason_no' },
                                                        { label: $filter('translate')('B0205.leanModule.list.reason_name'), code: 'reason_name' },
                                                        { label: $filter('translate')('B0205.leanModule.list.reason_level'), code: 'reason_level' },
                                                        { label: $filter('translate')('B0205.leanModule.list.abnormal_reason'), code: 'invalidity' },
                                                        { label: $filter('translate')('B0205.leanModule.list.wait_time'), code: 'reason_time' },
                                                    ],
                                                    query: function (conditions, feedback) {
                                                        var list = [];
                                                        $MMWService.pageNumberInfoGet({
                                                            form_name: 'PageNo_39',
                                                            query_condition_info: [
                                                                { column_name: 'a.OpNO', query_mode: '0', value: plotInfo.op_no },
                                                            ]
                                                        }, function (itemList) {
                                                            if (itemList && itemList.length > 0) {
                                                                itemList.forEach(function (item) {
                                                                    var isChosen = false;
                                                                    for (var i = 0; i < dialog.waitReasonList.length; i++) {
                                                                        // 不顯示已選擇的等待原因
                                                                        if (dialog.waitReasonList[i].reason_no == item.reason_no) {
                                                                            isChosen = true;
                                                                            break;
                                                                        }
                                                                    }
                                                                    if (!isChosen) {
                                                                        list.push(item);
                                                                    }
                                                                });
                                                            }
                                                            feedback(list);
                                                        });
                                                    },
                                                    confirm: function (selectItem, dialogQuery) {
                                                        dialog.waitReasonList.push({
                                                            reason_no: selectItem.reason_no,
                                                            reason_name: selectItem.reason_name,
                                                            reason_level: selectItem.reason_level,
                                                            invalidity: selectItem.invalidity,
                                                            reason_time: selectItem.reason_time
                                                        });
                                                        dialogQuery.hide();
                                                    }
                                                });
                                            }
                                        },
                                        'B0205_Serial_Number_Collecte_tmpPCSNo': {
                                            change: (tmpPCSNo, { event }) => {
                                                dialog.enter_PCSNo(event);
                                            }
                                        },
                                        // 20230223 modify by 文蔚 for M#128731: 使返回按鈕可以回到上一頁，而非第一頁
                                        'PageChange' :(formEntity) =>{ 
                                            if (dialog._nowForm == 'B0206_Collected_PCSNo') {
                                                dialog.changeForm('B0205_Serial_Number_Collecte')
                                            } else {
                                                dialog._nowForm = formEntity.name;
                                                dialog._title = formEntity.displayText;
                                            }
                                        }
                                    },
                                    _fn: {
                                        // 20230222 add by Alan for #128539: 修正進入序列号收集页面未呼叫API的問題
                                        'B0205_B0205_Serial_Number_Collecte': {
                                            isShown: op_plugin ? 'Y' : 'N',
                                            afterClick: () => dialog.openPCSNo()
                                        },
                                        'B0205_NCFileDownload': {//20220602 add by 翰鴻 for M#112917
                                            isShown: op_plugin?'Y':'N',
                                            click: ()=>{
                                                var xhr = new XMLHttpRequest();
                                                xhr.open('GET', dialog.FilePath);
                                                xhr.responseType = 'blob';
                                                xhr.onload = function () {
                                                    var a = document.createElement('a')
                                                    a.download = dialog.hiddenFileName;
                                                    a.rel = 'noopener';
                                                    a.href = URL.createObjectURL(xhr.response);
                                                    setTimeout(function () { URL.revokeObjectURL(a.href) }, 4E4);
                                                    setTimeout(function () {
                                                        try {
                                                            a.dispatchEvent(new MouseEvent('click'))
                                                        } catch (e) {
                                                            var evt = document.createEvent('MouseEvents')
                                                            evt.initMouseEvent('click', true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null);
                                                            a.dispatchEvent(evt)
                                                        }
                                                    }, 0);
                                                }
                                                xhr.onerror = function () {
                                                    console.error('could not download file')
                                                }
                                                xhr.send() 
                                            }
                                        },
                                        'B0205_WaitReason': {
                                            displayText: $filter('translate')('B0205.leanModule.wait_reason'),
                                            click: () => {
                                                dialog.changeForm('B0205_wait_reason');
                                            }
                                        },
                                        'B0205_collect': {
                                            displayText: $filter('translate')('B0205.lotnoinfocollect.title'),
                                            isShown: (plotCollectInfo && plotCollectInfo.length > 0) ? 'Y' : 'N',
                                            click: () => {
                                                if (dialog.plotCollectInfo && dialog.plotCollectInfo.length > 0) {
                                                    dialog.mode = 'lean-collect';
                                                    dialog.production_inf_detail_backup = angular.merge([], dialog.plotCollectInfo);

                                                    dialog.changeForm('B0205_production_inf_detail');
                                                } else {
                                                    $rootScope.showAlert($filter('translate')('B0206.showAlert.production_inf_detail_empty'));
                                                }

                                            }
                                        },
                                        'B0205_confirm': {
                                            click: () => {
                                                if (dialog.NCType) {
                                                    dialog.plotInfo.NCFileName = dialog.NCName;
                                                    dialog.plotInfo.NCFileVersion = "-1";
                                                }
                                                else {
                                                    dialog.plotInfo.NCFileName = dialog.hiddenFileName;
                                                    dialog.plotInfo.NCFileVersion = dialog.hiddenFileVersion;
                                                }


                                                if (dialog.plotSaveCollectInfo.length == 0 && dialog.plugin == '3' && dialog.plotCollectInfo.length != 0) {
                                                    $rootScope.showAlert($filter('translate')('B0206.msg.production_inf_require'), function () {
                                                    });
                                                    dialog.collect();
                                                    return
                                                } else if (dialog.plotInfo.qty == 0 || dialog.plotInfo.qty === undefined) {
                                                    $rootScope.showAlert($filter('translate')('B0205.showAlert.column1'), function () {
                                                        dialog.plotInfo.qty = '';
                                                    });
                                                    return
                                                }
                                                if ((+dialog.plotInfo.check_in_qty) < (+dialog.plotInfo.qty)) {
                                                    $rootScope.showAlert($filter('translate')('B0205.msg.column1') + dialog.plotInfo.qty
                                                        + $filter('translate')('B0205.msg.column2') + dialog.plotInfo.check_in_qty, function () {
                                                            dialog.plotInfo.qty = dialog.plotInfo.check_in_qty;
                                                        });
                                                    return
                                                }

                                                var callback = function () {
                                                    //69327 進站時將產線狀態改為加工
                                                    var content = {};
                                                    var plan_work = {
                                                        date: nowdatetime.split(' ')[0],
                                                        time: nowdatetime.split(' ')[1]
                                                    };
                                                    var work_time = $filter('date')(plan_work.date, 'yyyy/MM/dd') + " " + plan_work.time;
                                                    content = {
                                                        machine_no: machine.area_no,
                                                        report_datetime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                                                        machine_status: '0',
                                                        remark: '',
                                                        handle_user_no: config.cache.account,
                                                        plan_start_time: plot.machine_status == '0' || plot.machine_status == '1' ? '' : work_time,
                                                        actual_end_time: plot.machine_status == '0' || plot.machine_status == '1' ? work_time : '',
                                                        remarks: undefined
                                                    };
                                                    //回傳
                                                    //service.SMES_PlotCheckInProcess({
                                                    PlotCheckInProcess({
                                                        machine_no: dialog.machine_no,
                                                        plotInfo: dialog.plotInfo,
                                                        wait_detail: dialog.waitReasonList,
                                                        feedback: function () {
                                                            dialog.hide();
                                                            if (feedback)
                                                                feedback(content);
                                                        },
                                                        // 20200225 modify by WeiTing for M#67346 - 注塑 - 把 recipe_list 傳到 Inject01。
                                                        recipe_list: {
                                                            plot_no: plot.plot_no,
                                                            machine_no: dialog.machine_no,
                                                            machine_name: machine.machine_name,
                                                            product_no: plot.item_no,
                                                            product_name: plot.item_name,
                                                            op_no: plot.op_no
                                                        },
                                                        dialogB0205: function () {
                                                            dialog.hide();
                                                        },
                                                        insertdata: dialog,
                                                        IsInjectionMolding: dialog.IsInjectionMolding,
                                                        op_plug_in_detail: [{
                                                            op_plug_in: dialog.op_plug_in,
                                                            heat_plot_no: dialog.heat_plot_no
                                                        }]
                                                        //20210519 Modify by德義家興for#90580
                                                    }, dialog);
                                                }
                                                var content = {
                                                    plot_check_in: [
                                                        {
                                                            plot_no: dialog.plotInfo.plot_no,
                                                            op_no: dialog.plotInfo.op_no,
                                                            qty: dialog.plotInfo.qty,
                                                            machine_no: dialog.machine_no,
                                                        }
                                                    ]
                                                }
                                                material_check_for_checkin_process(content, callback);
                                            }
                                        },
                                        'B0205_wait_reason_confirm': {
                                            click: () => {
                                                dialog.waitReasonConfirm();
                                            }
                                        },
                                        'B0205_Serial_Number_Collecte_Execute': {
                                            click: () => {
                                                dialog.PCSNoConfirm();
                                            }
                                        },
                                        'B0205_Serial_Number_Collecte_opem_Collected': {
                                            click: () => {
                                                dialog.changeForm('B0206_Collected_PCSNo');

                                            }  
                                        },
                                        'B0205_production_inf_detail_Execute': {
                                            click: () => {
                                                dialog.plotCollectInfo = angular.merge([], dialog.production_inf_detail_backup);
                                                dialog.productionInfConfirm();
                                            }
                                        },
                                        // 20230220 add by Alan for #0128271: 補上生产信息检验不合格项
                                        'B0205_Lean_Check_close': {
                                            displayText: $filter('translate')('B0205.lotnoinfoCheck.btn.cancle'),
                                            click: () => dialog.cancle()
                                        },
                                        'B0205_Lean_Check_force': {
                                            displayText: $filter('translate')('B0205.lotnoinfoCheck.btn.force'),
                                            click: () => dialog.force()
                                        },
                                    },
                                    hide: function () {
                                        if (dialog.mode == 'PCSNo') {
                                            if (dialog.PCSNoList_count >= 1) {
                                                dialog.update_PlotInfo_Qty();
                                            }
                                            dialog.mode = 'trackIn';
                                        }else{
                                            _hide();
                                        }                                    
                                    },
                                    trackInVehicleQty: function(event, VehicleQty){ // 雙單位計算進站數量
                                        //依照need_vehicle判斷進站是否需要維護載具資訊
                                        if(!dialog.plotInfo.fastening_info_detail.vehicle_name
                                            || dialog.plotInfo.fastening_info_detail.vehicle_name == ''){
                                            if(dialog.plotInfo.fastening_info_detail.need_vehicle == 2){
                                                //無維護載具編號，請問是否繼續執行
                                                $rootScope.showAlert($filter('translate')('B0206.msg.vehicle_info_empty'));
                                                return;
                                            }
                                        }   
                                        var target = event.currentTarget;
                                        angular.element(target).addClass('is-focus');
                                        if(dialog.plotInfo.fastening_info_detail.molecule > 0 && dialog.plotInfo.fastening_info_detail.denominator > 0){
                                            $calculater.open(function(num,calcDialog){
                                                angular.element(target).removeClass('is-focus');
                                                if(+num <= 0){
                                                    // 雙單位數量不能小於等於0
                                                    $rootScope.showAlert($filter('translate')('B0205.vehicleMsg.column6'));
                                                } else {
                                                    var _checkout_qty = dialog.trackInVehicleQtyCallback(+num);
                                                    if(_checkout_qty > 0){
                                                        if(_checkout_qty > dialog.plotInfo.workstation_detail[0].check_in_qty){
                                                            // 轉換數量 + _checkout_qty + 超出可進站數量 + dialog.plotInfo.workstation_detail[0].check_in_qty +，轉換失敗，請重新輸入
                                                            return $rootScope.showAlert($filter('translate')('B0205.vehicleMsg.column1') + _checkout_qty 
                                                                + $filter('translate')('B0205.vehicleMsg.column4') + dialog.plotInfo.workstation_detail[0].check_in_qty
                                                                + $filter('translate')('B0205.vehicleMsg.column7'));
                                                        } else {
                                                            dialog.plotInfo.fastening_info_detail.double_unit_qty = (+num);
                                                            dialog.plotInfo.fastening_info_detail.vehicle_qty = _checkout_qty;
                                                            dialog.plotInfo.qty = _checkout_qty;
                                                            calcDialog.hide();
                                                        }
                                                    } else {
                                                        // 轉換數量 + _checkout_qty + 小於等於0，轉換失敗，請重新輸入
                                                        return $rootScope.showAlert($filter('translate')('B0205.vehicleMsg.column1') + _checkout_qty 
                                                            + $filter('translate')('B0205.vehicleMsg.column2') + $filter('translate')('B0205.vehicleMsg.column7'));
                                                    }
                                                }
                                            },
                                            function(calcDialog){
                                                angular.element(target).removeClass('is-focus');
                                                calcDialog.hide();
                                            },
                                            {
                                                defaultNum : VehicleQty,
                                                decimal : true
                                            });
                                        } else {
                                            // 雙單位轉換率分子或分母不得為0
                                            $rootScope.showAlert($filter('translate')('B0205.vehicleMsg.column3'));
                                        }
                                    },
                                    trackInVehicleQtyCallback: function(num){ // 雙單位計算進站數量callback
                                        var _checkout_qty = CaculateFastening(dialog.plotInfo.fastening_info_detail, (+num));
                                        if(dialog.plotInfo.fastening_info_detail.double_unit_rules == 3){ // 3: 转换数量超出可进站数则取可进站数
                                            if(+_checkout_qty > +dialog.plotInfo.workstation_detail[0].check_in_qty){
                                                _checkout_qty = +dialog.plotInfo.workstation_detail[0].check_in_qty;
                                            }
                                        } else if(dialog.plotInfo.fastening_info_detail.double_unit_rules == 4){ // 4: 转换数量小于可进站数取可进站数
                                            if(+_checkout_qty < +dialog.plotInfo.workstation_detail[0].check_in_qty){
                                                _checkout_qty = +dialog.plotInfo.workstation_detail[0].check_in_qty;
                                            }
                                        }
                                        return +_checkout_qty || 0;
                                    },
                                    changeMoleculeValue: function(event){ // 更換雙單位轉換率分子
                                        var target = event.currentTarget;
                                        angular.element(target).addClass('is-focus');
                                        $calculater.open(function(num,calcDialog){
                                            angular.element(target).removeClass('is-focus');
                                            if(dialog.plotInfo.fastening_info_detail.double_unit_qty){
                                                var originMoleculeValue = dialog.plotInfo.fastening_info_detail.molecule; // 先保留原本的轉換率分子
                                                if(+num == 0){
                                                    // 已經輸入雙單位數量，不能變更為0
                                                    return $rootScope.showAlert($filter('translate')('B0205.vehicleMsg.column5'));
                                                } else {
                                                    dialog.plotInfo.fastening_info_detail.molecule = (+num); // 先更換轉換率分子進行計算，轉換失敗會在還原
                                                    var _checkout_qty = dialog.trackInVehicleQtyCallback(+dialog.plotInfo.fastening_info_detail.double_unit_qty);
                                                    if(_checkout_qty > 0){
                                                        if(_checkout_qty > dialog.plotInfo.workstation_detail[0].check_in_qty){
                                                            dialog.plotInfo.fastening_info_detail.molecule = originMoleculeValue; // 轉換失敗，需還原原本的轉換率分子
                                                            // 轉換數量 + _checkout_qty + 超出可進站數量 + dialog.plotInfo.workstation_detail[0].check_in_qty +，轉換失敗，請重新輸入
                                                            return $rootScope.showAlert($filter('translate')('B0205.vehicleMsg.column1') + _checkout_qty 
                                                                + $filter('translate')('B0205.vehicleMsg.column4') + dialog.plotInfo.workstation_detail[0].check_in_qty
                                                                + $filter('translate')('B0205.vehicleMsg.column7'));
                                                        } else {
                                                            dialog.plotInfo.fastening_info_detail.molecule = (+num);
                                                            dialog.plotInfo.fastening_info_detail.vehicle_qty = _checkout_qty;
                                                            dialog.plotInfo.qty = _checkout_qty;
                                                            calcDialog.hide();
                                                        }
                                                    } else {
                                                        // 轉換數量 + _checkout_qty + 小於等於0，轉換失敗，請重新輸入
                                                        return $rootScope.showAlert($filter('translate')('B0205.vehicleMsg.column1') + _checkout_qty 
                                                            + $filter('translate')('B0205.vehicleMsg.column2') + $filter('translate')('B0205.vehicleMsg.column7'));
                                                    }
                                                }
                                            } else {
                                                dialog.plotInfo.fastening_info_detail.molecule = (+num);
                                                calcDialog.hide();
                                            }
                                        },
                                        function(calcDialog){
                                            angular.element(target).removeClass('is-focus');
                                            calcDialog.hide();
                                        },
                                        {
                                            defaultNum : dialog.plotInfo.fastening_info_detail.molecule,
                                            decimal : true
                                        });
                                    },
                                    changeDenominatorValue: function(event){ // 更換雙單位轉換率分母
                                        var target = event.currentTarget;
                                        angular.element(target).addClass('is-focus');
                                        $calculater.open(function(num,calcDialog){
                                            angular.element(target).removeClass('is-focus');
                                            var originDenominatorValue = dialog.plotInfo.fastening_info_detail.denominator; // 先保留原本的轉換率分母
                                            if(dialog.plotInfo.fastening_info_detail.double_unit_qty){
                                                if(+num == 0){
                                                    // 已經輸入雙單位數量，不能變更為0
                                                    return $rootScope.showAlert($filter('translate')('B0205.vehicleMsg.column5'));
                                                } else {
                                                    dialog.plotInfo.fastening_info_detail.denominator = (+num); // 先更換轉換率分母進行計算，轉換失敗會在還原
                                                    var _checkout_qty = dialog.trackInVehicleQtyCallback(+dialog.plotInfo.fastening_info_detail.double_unit_qty);
                                                    if(_checkout_qty > 0){
                                                        if(_checkout_qty > dialog.plotInfo.workstation_detail[0].check_in_qty){
                                                            dialog.plotInfo.fastening_info_detail.denominator = originDenominatorValue;
                                                            // 轉換數量 + _checkout_qty + 超出可進站數量 + dialog.plotInfo.workstation_detail[0].check_in_qty +，轉換失敗，請重新輸入
                                                            return $rootScope.showAlert($filter('translate')('B0205.vehicleMsg.column1') + _checkout_qty 
                                                                + $filter('translate')('B0205.vehicleMsg.column4') + dialog.plotInfo.workstation_detail[0].check_in_qty
                                                                + $filter('translate')('B0205.vehicleMsg.column7'));
                                                        } else {
                                                            dialog.plotInfo.fastening_info_detail.denominator = (+num);
                                                            dialog.plotInfo.fastening_info_detail.vehicle_qty = _checkout_qty;
                                                            dialog.plotInfo.qty = _checkout_qty;
                                                            calcDialog.hide();
                                                        }
                                                    } else {
                                                        // 轉換數量 + _checkout_qty + 小於等於0，轉換失敗，請重新輸入
                                                        return $rootScope.showAlert($filter('translate')('B0205.vehicleMsg.column1') + _checkout_qty 
                                                            + $filter('translate')('B0205.vehicleMsg.column2') + $filter('translate')('B0205.vehicleMsg.column7'));
                                                    }
                                                } 
                                            } else {
                                                dialog.plotInfo.fastening_info_detail.denominator = (+num);
                                                calcDialog.hide();
                                            }
                                        },
                                        function(calcDialog){
                                            angular.element(target).removeClass('is-focus');
                                            calcDialog.hide();
                                        },
                                        {
                                            defaultNum : dialog.plotInfo.fastening_info_detail.denominator,
                                            decimal : true
                                        });
                                    },
                                    keyVehicleList:function(event){ // 掃描載具編號
                                        if(event.keyCode == 13){
                                            if(dialog.plotInfo.fastening_info_detail.vehicle_no && dialog.plotInfo.fastening_info_detail.vehicle_no != ''){
                                                vehicle_no_info_get(dialog.plotInfo.fastening_info_detail.vehicle_no, function(items){
                                                    if(items && items.length > 0){
                                                        dialog.plotInfo.fastening_info_detail.vehicle_no = items[0].vehicle_no;
                                                        dialog.plotInfo.fastening_info_detail.vehicle_name = items[0].vehicle_name;
                                                        dialog.plotInfo.fastening_info_detail.vehicle_weight = items[0].vehicle_weight;
                                                        dialog.plotInfo.fastening_info_detail.vehicle_capacity = items[0].vehicle_capacity;
                                                        dialog.plotInfo.fastening_info_detail.double_unit_qty = undefined; // 有載具編號的情況，雙單位計算公式會不同，所以刷新載具編號時，也要重新輸入雙單位數量
                                                    } else {
                                                        $rootScope.showAlert($filter('translate')('common.msg.no_data'));
                                                        dialog.plotInfo.fastening_info_detail.vehicle_no = '';
                                                        dialog.plotInfo.fastening_info_detail.vehicle_name = '';
                                                        dialog.plotInfo.fastening_info_detail.vehicle_weight = '';
                                                        dialog.plotInfo.fastening_info_detail.vehicle_capacity = '';
                                                    }
                                                });
                                            } else {
                                                dialog.plotInfo.fastening_info_detail.vehicle_no = '';
                                                dialog.plotInfo.fastening_info_detail.vehicle_name = '';
                                                dialog.plotInfo.fastening_info_detail.vehicle_weight = '';
                                                dialog.plotInfo.fastening_info_detail.vehicle_capacity = '';
                                            }
                                        }
                                    },
                                    input_qty: function(event){
                                        var target = event.currentTarget;
                                        angular.element(target).addClass('is-focus');
                                        $calculater.open(function(num,calcDialog){
                                            angular.element(target).removeClass('is-focus');
                                            dialog.plotInfo.qty = (+num);
                                            //dialog.plotInfo.QTYACIO = dialog.plotInfo.qty*((+dialog.plotInfo.C_Numerator)/(+dialog.plotInfo.C_Denominator));
                                            dialog.plotInfo.QTYACIO = CaculatQTYACIO(dialog.plotInfo);
                                            calcDialog.hide();
                                            document.querySelector(".searching-func").focus();
                                        },
                                        function(calcDialog){
                                            angular.element(target).removeClass('is-focus');
                                            calcDialog.hide();
                                        },
                                        {
                                            title : $filter('translate')('B0205.calculater-title'),
                                            defaultNum : dialog.plotInfo.qty,
                                            decimal : true
                                        });
                                    },
                                    // 精實模組
                                    waitReason: function() {
                                        dialog.mode = 'lean-waitReason';
                                        // 點擊等待原因按鈕複製當前的等待原因項目，避免使用者回上一頁時，有後悔修改或誤刪資料的情況。
                                        dialog.waitReasonListCopy = angular.copy(dialog.waitReasonList);
                                    },
                                    prevTrackIn: function(){
                                        dialog.mode = 'trackIn';
                                        // 回上一頁都不進行資料更新。
                                        dialog.waitReasonList = dialog.waitReasonListCopy;
                                        $timeout(function(){
                                            document.querySelector(".searching-func").focus();
                                        }); 
                                    },
                                    func_scan:function(event){
                                        if(event.keyCode == 13){
                                            if(dialog.scan_func_val==='ORD_000_A005'){
                                                dialog.waitReason();
                                                $timeout(function(){
                                                    document.querySelector(".searching-wait-reason").focus();
                                                });
                                            } else if (dialog.scan_func_val === 'ORD_000_A008') {//確定
                                                dialog._fn['B0205_confirm'].click();
                                            }else if(dialog.scan_func_val==='ORD_000_A009'){//關閉
                                                dialog.hide();
                                            }else{
                                                $rootScope.showAlert($filter('translate')('B0205.showAlert.column4'));
                                            }
                                            dialog.scan_func_val='';
                                        }
                                    },
                                    //QRCode輸入
                                    qrcode_plot_no : function(){
                                        $rootScope.OpenScanner({
                                            after : function(result){
                                                input_plot_no_callback(result.text);
                                            },
                                            exception: function(){
                                                //目前裝置無法使用相機
                                                $rootScope.showAlert($filter('translate')('B0214.showAlert.column3'));
                                            },
                                            orientation : 'landscape'
                                        });
                                    },
                                    searchWaitReasonList: function(event){
                                        if(event.keyCode == 13){
                                            if(dialog.searchWaitReason === "ORD_000_A008" && dialog.open_scan_column === true){//如果掃描A008指令就回上一頁
                                                dialog.waitReasonConfirm();
                                                dialog.searchWaitReason='';
                                                $timeout(function(){
                                                    document.querySelector(".searching-func").focus();
                                                });
                                            }else if(dialog.searchWaitReason === "ORD_000_A009" && dialog.open_scan_column === true){//關閉
                                                dialog.hide();
                                            }else if(dialog.searchWaitReason === "ORD_000_A012" && dialog.open_scan_column === true){//返回
                                                dialog.prevTrackIn();
                                                dialog.searchWaitReason='';
                                                $timeout(function(){
                                                    document.querySelector(".searching-func").focus();
                                                }); 
                                            }else{
                                                $MMWService.pageNumberInfoGet({
                                                    form_name: 'PageNo_39',
                                                    query_condition_info:[
                                                        {column_name:'a.OpNO', query_mode:'0', value: plotInfo.op_no},
                                                        {column_name:'b.REASONNO', query_mode:'2', value: dialog.searchWaitReason},
                                                    ]
                                                }, function(itemList){
                                                    dialog.searchWaitReason='';
                                                    if(itemList && itemList.length > 0){
                                                        itemList.forEach(function(item){
                                                            var isChosen = false;
                                                            for(var i = 0; i < dialog.waitReasonList.length; i++){
                                                                // 不能輸入已選擇的等待原因，或重複輸入相同的等待原因。
                                                                if(dialog.waitReasonList[i].reason_no == item.reason_no){
                                                                    isChosen = true;
                                                                    break;
                                                                }
                                                            }
                                                            if(!isChosen){
                                                                dialog.waitReasonList.push(item);
                                                            } else {
                                                                $rootScope.showAlert($filter('translate')('B0205.msg.this_reason_has_been_entered'));
                                                            };
                                                        });
                                                    } else {
                                                        $rootScope.showAlert($filter('translate')('B0205.msg.no_match_wait_reason'));
                                                    }
                                                });
                                            }
                                        
                                        };
                                    },
                                    removeRow: function (item) {
                                        dialog.waitReasonList.splice(item, 1);
                                        document.querySelector(".searching-wait-reason").focus();
                                    },
                                    waitReasonConfirm: function() {
                                        if(dialog.waitReasonList.length > 0){
                                            // 取出所有的等待時間。
                                            var allReasonTime = dialog.waitReasonList.map(function(item){
                                                return +(item.reason_time);
                                            });
                                            // 解決 JS浮點數問題 - 參考底層 decimalAdd 方法 -- start
                                            var sum = 0;
                                            var point_length = [];
                                            var m;
                                            for(var i = 0; i < allReasonTime.length; i++){
                                                // 取出所有等待時間的小數點位數的長度
                                                if(allReasonTime[i].toString().split(".")[1] == undefined){
                                                    point_length.push(0);      
                                                } else {
                                                    point_length.push(allReasonTime[i].toString().split('.')[1].length);
                                                };
                                                
                                                m = Math.pow(10, Math.max.apply(null, point_length));

                                                sum += Math.round(allReasonTime[i] * m);

                                                var finally_reasonTime = (sum / m);
                                            };
                                            // 解決 JS浮點數問題 - 參考底層 decimalAdd 方法 -- end
                                            dialog.waitReasonTime = finally_reasonTime;
                                            dialog.mode = 'trackIn';
                                        } else {
                                            // 沒選擇等待原因項目，都顯示 0 分。
                                            dialog.waitReasonTime = 0;
                                            dialog.mode = 'trackIn';
                                        };
                                        dialog.changeForm('B0205');
                                        $timeout(function(){
                                            if(document.activeElement.tagName != 'INPUT' ){
                                                document.querySelector(".searching-func").focus();
                                            }
                                        }); 
                                    },
                                    //20210519 Modify by德義家興for#90580
                                    //進入序列號收集
                                    openPCSNo: function(){
                                        //20221108 modify by 翰鴻 for M#116946
                                        getPCSNoList(function (list, collected_PCSNo){
                                            if (list == undefined) {
                                                dialog.PCSNoList = [];
                                                dialog.PCSNoList_count = 0;
                                                dialog.collected_PCSNo = [];
                                            }else{
                                                dialog.PCSNoList = list;
                                                dialog.PCSNoList_count = list.length;    
                                                dialog.collected_PCSNo = collected_PCSNo;
                                            }
                                            //console.log('PCSNoList',list);
                                        })
                                        dialog.mode = 'PCSNo';
                                        if(!$rootScope.onDevice){//如果在電腦上就啟動鼠標定位
                                            $timeout(function(){
                                                document.querySelector(".searching-PCSNo").focus();
                                            });  
                                        }
                                    },
                                    //QRCode輸入
                                    qrcode_PCSNo: function(){
                                        $rootScope.OpenScanner({
                                            after: function (result) {
                                                check_PCSNo(result.text);
                                                dialog.tmpPCSNo = "";
                                                document.querySelector(".searching-PCSNo").focus();
                                            },
                                            exception: function () {
                                                //目前裝置無法使用相機
                                                $rootScope.showAlert($filter('translate')('B0214.showAlert.column3'));
                                            },
                                            orientation: 'landscape'
                                        });
                                    },
                                    //
                                    enter_PCSNo: function(event){
                                        if (event.keyCode == 13 && dialog.tmpPCSNo.length != 0) {
                                            //檢查重複
                                            dialog.check_PCSNo(dialog.tmpPCSNo);
                                            dialog.tmpPCSNo = "";
                                        }
                                    },
                                    //掃碼
                                    insert_PCSNo: function(pcs_no){
                                        var content = {
                                            op_no: plot.op_no,
                                            pcs_no: pcs_no,
                                            lot_no: plot.plot_no,
                                            equipment_no: machine.machine_no,
                                            collection_type: '0', //0=進站, 1=出站
                                        };
                                        $MMWService.sendToServer({
                                            uri: 'ServicesSTD.Module_WIP.serial_num_collecting_check',
                                            content : content,
                                            success : function(data){
                                                if (data.msg.indexOf('error') == -1) {
                                                    //console.log("成功新增",data);
                                                }else{
                                                    $rootScope.showAlert($filter('translate')('B0206.msg.Previous_workstation') + data.from_node_no + $filter('translate')('B0206.msg.PCSNo'));
                                                }
                                                dialog.openPCSNo();
                                            }
                                        });                
                                    },
                                    //檢查重複
                                    check_PCSNo: function(pcs_no){
                                        var checkStr = '';
                                        dialog.PCSNoList.forEach(function(item){
                                            checkStr += item.pcs_no;
                                        });
                                        if (checkStr.indexOf(pcs_no) == -1) { //不重複
                                            dialog.insert_PCSNo(pcs_no);
                                        }else{
                                            $rootScope.showConfirm($filter('translate')('B0206.msg.PCSNo_has_been_duplicated'), function (Confirm) {
                                                Confirm.hide();
                                                dialog.insert_PCSNo(pcs_no);
                                            });
                                        }
                                    },
                                    //刪除PCSNO
                                    delete_PCSNo: function(item,all_item){
                                        $rootScope.showConfirm($filter('translate')('B0206.msg.You_sure_you_want_to_delete_it'), function (Confirm) {
                                            Confirm.hide();
                                            
                                            var PCSNo = [];
                                            if (all_item == undefined) {
                                                PCSNo.push(item.pcs_no);
                                            }else{
                                                PCSNo = all_item;
                                            }
                                            var content = {
                                                equipment_no: machine.machine_no,
                                                lot_no: plot.plot_no,
                                                op_no: plot.op_no,
                                                collection_type: "0", //0=進站, 1=出站
                                                pcs_no: PCSNo,
                                            };
                                            $MMWService.sendToServer({
                                                uri: 'ServicesSTD.Module_WIP.delete_serial_num_process',
                                                content : content,
                                                success : function(data){
                                                    //console.log("成功刪除");
                                                    dialog.openPCSNo();
                                                }
                                            });
                                        });
                                    },
                                    //刪除所有
                                    delect_all_PCSNo: function(){
                                        if (dialog.PCSNoList.length > 0) {
                                            var arr_PCSNo = [];

                                            dialog.PCSNoList.forEach(function(item){
                                                arr_PCSNo.push(item.pcs_no);
                                            });
                                            dialog.delete_PCSNo("A",arr_PCSNo);
                                        }
                                    },
                                    //序列號收集 回前頁
                                    PCSNo_back: function(){
                                        if (dialog.PCSNoList_count >= 1) {
                                            dialog.update_PlotInfo_Qty();
                                        }
                                        dialog.mode = 'trackIn';
                                        $timeout(function(){
                                            document.querySelector(".searching-func").focus();
                                        }); 
                                    },
                                    //序列號收集 確認紐
                                    PCSNoConfirm: function(){
                                        if (dialog.PCSNoList_count >= 1) {
                                            dialog.update_PlotInfo_Qty();
                                        }
                                        dialog.mode = 'trackIn';
                                        //console.log('PCSNoList',dialog.PCSNoList);
                                        //console.log('plotInfo',dialog.plotInfo);
                                        //console.log('badReasonInfo',dialog.badReasonInfo);
                                        //console.log('PCSNoBadReasonList',dialog.PCSNoBadReasonList);
                                        dialog.changeForm('B0205');
                                    },
                                    //更新dialog.plotInfo.qty;進站數量
                                    update_PlotInfo_Qty: function(){
                                        dialog.plotInfo.qty = dialog.PCSNoList_count;
                                        dialog.plotInfo.QTYACIO = CaculatQTYACIO(dialog.plotInfo); //輸入qty時跑的原邏輯
                                    },
                                    loadNCCode: function () {
                                        $rootScope.showQueryList({
                                            header: [
                                                { label: $filter('translate')('B0205.NC_DDL.LotNo'), code: 'lotNO' },
                                                { label: $filter('translate')('B0205.NC_DDL.ProductNo'), code: 'ProductNO' },
                                                { label: $filter('translate')('B0205.NC_DDL.ProductVersion'), code: 'ProductVersion' },
                                                { label: $filter('translate')('B0205.NC_DDL.OPNO'), code: 'OPNo' },
                                                { label: $filter('translate')('B0205.NC_DDL.EquipmentNo'), code: 'EquipmentNO' },
                                                { label: $filter('translate')('B0205.NC_DDL.FileName'), code: 'FileName' },
                                                { label: $filter('translate')('B0205.NC_DDL.FileVersion'), code: 'FileVersion' }
                                            ],
                                            query: function (conditions, feedback) {
                                                //vehicle_no_info_get('', feedback);
                                                NCCode_info_get(feedback, dialog.plotInfo.plot_no, dialog.plotInfo.op_no, machine_no);
                                            },
                                            confirm: function (selectItem, query_dialog) {
                                                //20220607 modify by 翰鴻 for M#112917
                                                dialog.NCCode = DeleteEX(selectItem.FileName) + '-' + selectItem.FileVersion + GetEX(selectItem.FileName);
                                                //隱藏欄位
                                                dialog.hiddenFileName = selectItem.FileName;
                                                dialog.hiddenFileVersion = selectItem.FileVersion;
                                                //20220602 add by 翰鴻 for M#112917
                                                var serverAddress = 'http://' + config.server.ip + ':' + config.server.port + '/';
                                                // 20230818 modify by wenwei for M#142322 NC代码档案下载错误
                                                dialog.FilePath = `${serverAddress}${config.server.name}/ncFiles/${selectItem.ProductNO}_${selectItem.ProductVersion}/${selectItem.OPNo}/${selectItem.EquipmentNO}/${selectItem.DocFileName}`;
                                                query_dialog.hide();
                                            }
                                        });

                                    },
                                    beforeShown: function () {
                                        $MMWService.sendToServer({
                                            uri: 'ServicesSTD.Module_WIP.NCCode_info_get',
                                            content: {
                                                LotNO: dialog.plotInfo.plot_no,
                                                OPNO: dialog.plotInfo.op_no,
                                                EquipmentNO: machine_no
                                            },
                                            success: function (data) {
                                                if (data.length > 0) {
                                                    //20220607 modify by 翰鴻 for M#112917
                                                    dialog.NCCode = DeleteEX( data[0].FileName) + '-' + data[0].FileVersion + GetEX(data[0].FileName);
                                                    dialog.hiddenFileName = data[0].FileName;
                                                    dialog.hiddenFileVersion = data[0].FileVersion;
                                                    //20220602 add by 翰鴻 for M#112917
                                                    var serverAddress = 'http://' + config.server.ip + ':' + config.server.port + '/';
                                                    // 20230818 modify by wenwei for M#142322 NC代码档案下载错误
                                                    dialog.FilePath = `${serverAddress}${config.server.name}/ncFiles/${data[0].ProductNO}_${data[0].ProductVersion}/${data[0].OPNo}/${data[0].EquipmentNO}/${data[0].DocFileName}`;
                                                }                                            
                                            }
                                        });
                                    },
                                    // 生产信息收集
                                    collect: function () {
                                        // 20230220 add by Alan for #0128271: 補上生产信息检验不合格项
                                        if (dialog.plotCollectInfo && dialog.plotCollectInfo.length > 0) {
                                            dialog.mode = 'lean-collect';
                                            dialog.changeForm('B0205_production_inf_detail');
                                            dialog.production_inf_detail_backup = angular.merge([], dialog.plotCollectInfo);

                                        } else {
                                            $rootScope.showAlert($filter('translate')('B0206.showAlert.production_inf_detail_empty'));
                                        }
                                    },
                                    switchInit: function (item) {
                                        if (!item.productioninf_value) {
                                            item.productioninf_value = '0';
                                        }
                                    },
                                    switchClick: function (item) {
                                        if (item.productioninf_value == '0') {
                                            item.productioninf_value = '1';
                                        } else {
                                            item.productioninf_value = '0';
                                        }
                                    },
                                    // 20230220 add by Alan for #0128271: 補上生产信息检验不合格项
                                    //回到生产资讯收集
                                    prevCheckIn: function () {
                                        dialog.mode = 'lean-collect';
                                        dialog.changeForm('B0205_production_inf_detail');
                                        // 回上一頁都不進行資料更新。
                                        dialog.plotCollectInfo = angular.merge([], dialog.production_inf_detail_backup);
                                        $timeout(function () {
                                            document.querySelector(".searching-func").focus();
                                        });
                                    },
                                    // 20230220 add by Alan for #0128271: 補上生产信息检验不合格项
                                    //生产资讯收集确定按钮
                                    productionInfConfirm: function () {

                                        var msg = '';
                                        if (dialog.mode == 'lean-collect') {
                                            msg = productionInfValidate(dialog.plotCollectInfo);

                                        }
                                        if (msg == '') {
                                            dialog.isRequire = false;
                                            dialog.plotSaveCollectInfo = dialog.plotCollectInfo;
                                            dialog.plotCollectInfo.forEach(function (item) {

                                                if (item.productioninf_code == 'StampingSpeed') {
                                                    //进行验证
                                                    $MMWService.sendToServer({
                                                        uri: 'ServicesSTD.Module_WIP.check_stampingspeed_info',
                                                        content: { plot_no: dialog.plotInfo.plot_no, equipment_no: machine.machine_no, op_no: plot.op_no, chechk_flg: 'true' },
                                                        success: function (data) {
                                                            stampingspeed = data.stampingspeed;
                                                            if (stampingspeed == item.productioninf_value) {
                                                                dialog.mode = 'trackIn';
                                                                dialog.changeForm('B0205');
                                                            } else {
                                                                dialog.mode = 'lean-check';
                                                                dialog.changeForm('B0205_Lean_Check');
                                                                //清空验证List
                                                                dialog.plotCheckInfo = [];
                                                                dialog.plotCheckInfo.push(item);
                                                            }

                                                        }
                                                    });

                                                } else {
                                                    dialog.mode = 'trackIn';
                                                    dialog.changeForm('B0205');
                                                }
                                            });
                                        } else {
                                            dialog.isRequire = true;
                                            $rootScope.showAlert(msg);
                                        }
                                    },
                                    // 20230220 add by Alan for #0128271: 補上生产信息检验不合格项
                                    //取消
                                    cancle: function () {
                                        dialog.mode = 'lean-collect';
                                        dialog.changeForm('B0205_production_inf_detail');
                                        // 回上一頁都不進行資料更新。
                                        dialog.plotCollectInfo = angular.merge([], dialog.production_inf_detail_backup);
                                        $timeout(function () {
                                            document.querySelector(".searching-func").focus();
                                        });
                                    },
                                    // 20230220 add by Alan for #0128271: 補上生产信息检验不合格项
                                    //强制
                                    force: function () {
                                        $mdDialog.serviceDialog('PasswordService', {
                                            mode: 'AreaLeader',
                                            equipmentno: machine_no,
                                            feedback: function (account, password, description) {
                                                //dialog.account = account;
                                                //dialog.password = password;
                                                //dialog.description = description;
                                                dialog.mode = 'trackIn';
                                                dialog.changeForm('B0205');
                                            }
                                        });
                                        

                                    },                                    
                                    //20221108 add by 翰鴻 for M#116946
                                    openCollectedPCSNo: function () {
                                        dialog.mode = 'collectedPCSNo';

                                    },
                                    PCSNoBack: function () {
                                        dialog.mode = 'PCSNo';
                                    },
                                    collectedPCSNo_back: function () {
                                        dialog.mode = 'PCSNo';
                                    }
                                };
                            }
                        );
                    })
                }

                function DeleteEX(FileName) {
                    var pos = FileName.lastIndexOf('.');
                    return FileName.substr(0, pos);
                }
                function GetEX(FileName) {
                    var pos = FileName.lastIndexOf('.');
                    return FileName.substr(pos);
                }

                //查询作业站属性
                (function getPlugIn() {
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_WIP.get_plugIn_data',
                        content: { op_no: plot.op_no, equipment_no: machine.machine_no, need: 'false' },
                        success: function (data) {
                            plugin = data.plugin;
                            plotCollectInfo = data.plot_detail;
                        }
                    });

                })();

                
                // 20220318 modify by Alan for M#104045: 調整物料檢查卡控時機
                //取得生產批資訊
                (function getPlotInfo() {
                    OpParameterInfo({
                        machine_no: machine_no,
                        is_line : type=='line'?'1':'0',
                        lot_no : plot.plot_no,
                        op_no : plot.op_no,
                        area_no : machine_no
                    }, function(){
                        var content = {
                            machine_no: machine_no,
                            plot_no: plot.plot_no,
                            op_seq: '',//
                            op_no: plot.op_no,
                            workstation_no: '',//
                            qty: '',
                            return_type: '1',
                            op_plug_in: plot.op_plug_in
                        };
                        $MMWService.sendToServer({
                            uri: 'ServicesSTD.Module_WIP.plot_info_get',
                            content: content,
                            success: function (data) {
                                if (data.MsgLevel == 0) {
                                    initPlotInfo(data, openDialog);
                                } else if (data.MsgLevel == 1) {
                                    $rootScope.showConfirm(data.SysMsg, function (confirmDialog) {
                                        confirmDialog.hide();
                                        initPlotInfo(data, openDialog);
                                    });
                                } else if (data.MsgLevel == 2) {
                                    $rootScope.showAlert(data.SysMsg);
                                }
                            }
                        });
                    });
                })();
                //20210519 Modify by德義家興for#90580
                //取得作業站屬性plugin
                function check_plugIn(callback){
                    var content = {
                        op_no: plot.op_no
                    };
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_MAT.check_plugIn',
                        content : content,
                        success : function(data){
                            //console.log('check_plugIn',data)
                            if (callback)
                            callback(data.qty);
                        }
                    });
                }
                //20210519 Modify by德義家興for#90580
                //判斷作業站屬性plugin是否=5; 5:CNC
                (function isPlugInEqualFive(){
                    check_plugIn(function(result){
                        if (parseInt(result,10) >= 1) {
                            //console.log('true')
                            op_plugin = true;
                        }else{
                            //console.log('false')
                            op_plugin = false;
                        }
                    })
                })();
                //20210519 Modify by德義家興for#90580
                //取得序列號收集的grid資料
                function getPCSNoList(callback){
                    var content = {
                        op_no: plot.op_no,
                        equipment_no: machine.machine_no,
                        lot_no: plot.plot_no,
                        collection_type: "0", //0=進站, 1=出站
                    };
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_WIP.serial_num_collecting_info_get',
                        content : content,
                        success : function(data){
                            //console.log('list',data);
                            if (callback) {
                                //20221108 modify by 翰鴻 for M#116946
                                callback(data.serial_num_collecting_info, data.collected_PCSNo);
                            }
                        },
                        error: function(data){
                            //console.log('no data!',data);
                            if (callback) {
                                callback(data.serial_num_collecting_info, data.collected_PCSNo);
                            }
                        }
                    });
                }
            };

            //重組生產批資訊
            function initPlotInfo(data, callback){
                if(data.plot_info_get.length > 0){
                    if(data.plot_info_get[0].workstation_detail.length>0){
                        // 爐批號 opPlugInDetail
                        var opPlugInDetail;
                        if(!data.op_plug_in_detail || data.op_plug_in_detail.length == 0)
                            opPlugInDetail = [];
                        else
                            opPlugInDetail = data.op_plug_in_detail[0];
                        
                        data = data.plot_info_get[0];
                        if(data.workstation_detail[0].labor_detail.length == 0){
                            $rootScope.showAlert($filter('translate')('B0205.showAlert.column3'));
                        } else {
                            plotInfo = data;
                            plotInfo = angular.merge(plotInfo, data.workstation_detail[0]);
                            // 20220330 modify by chenshibo for#108636：取AP时间
                            plotInfo.report_datetime = data.sysdate_time;
                            plotInfo.qty = (+plotInfo.check_in_qty);
                            //plotInfo.QTYACIO = CaculatQTYACIO(plotInfo);

                            // 精實模組 → 會預設帶(第)一筆等待原因。
                            var waitReasonList = [];
                            if(plotInfo.wait_detail && plotInfo.wait_detail.length > 0)
                                waitReasonList.push(plotInfo.wait_detail[0]);

                            if(callback){
                                if(config.cache.sys_parameter['FasteningPackage'] === '1'){
                                    fastening_info_get(plotInfo.plot_no, plotInfo.op_no, function(data){
                                        plotInfo.fastening_info_detail = data;
                                        callback(plotInfo, waitReasonList, opPlugInDetail);
                                    });
                                } else {
                                    callback(plotInfo, waitReasonList, opPlugInDetail);
                                }
                            } 
                        }
                    }else {
                        $rootScope.showAlert('workstation_detail is empty');
                    }
                } else {
                    $rootScope.showAlert('plot_info_get is empty');
                }
                $timeout(function(){
                    if(document.activeElement.tagName != 'INPUT' ){
                        document.querySelector(".searching-func").focus();
                    }
                }); 
            }

            //計算出站後數量
            function CaculatQTYACIO(plotInfo){
                var QTYACIO = $calculater.decimalMutiple((+plotInfo.qty), (+plotInfo.C_Numerator)/(+plotInfo.C_Denominator)),
                    C_Accuracy = Math.pow(10,plotInfo.C_Accuracy||0)||1;
                if(plotInfo.C_Mode == '0'){
                    //無條件進位
                    QTYACIO = Math.ceil(QTYACIO * C_Accuracy) / C_Accuracy;
                } else if(plotInfo.C_Mode == '1'){
                    //無條件捨位
                    QTYACIO = Math.floor(QTYACIO * C_Accuracy) / C_Accuracy;
                }
                return QTYACIO;
            }

            //模製具檢查
            function AccLifeCheck(machine_no, plotInfo, callback){
                var content = {
                    recordlist : [{
                        op_no : plotInfo.op_no,
                        plot_no: plotInfo.plot_no,
                        machine_no: machine_no,
                        qty : plotInfo.qty,
                    }
                ]};

                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_ACC.acc_life_check_process',
                    content : content,
                    success : function(data){
                        if(data.life_manage == '0'){
                            //警示
                            $rootScope.showConfirm(data.description, function(confirmDialog){
                                confirmDialog.hide();
                                if(callback)
                                    callback();
                            });
                        } else if(data.life_manage == '1'){
                            //暫停生產
                            $rootScope.showAlert(data.description);
                        } else if(data.life_manage == '2'){
                            //核准
                            if(callback)
                                callback();
                        }
                    }
                });
            }

            //檢查始業點檢狀態
            function OpParameterInfo(content, callback){
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.start_in_op_parameter_info_get',
                    content : content,
                    success : function(data){
                        var errorMsg = '', warningMsg = '';
                        //生產線時(is_line=1)且需要始業檢查(isCheckSW = 1)時始業點檢須為全通過(isCheckEQP=2)
                        if(content.is_line == '1' && data.isCheckSW == 1 ){
                            if(data.start_check_result != 2){
                                //始業點檢尚未通過，不可進站
                                errorMsg +=$filter('translate')('B0205.msg.starting_check_fail')+'<br>';
                            }
                        }

                        //需要點檢檢查(alert_mode  = 2)
                        if(data.alert_mode == 2 ){
                            errorMsg += data.alert_msg ;
                        } else if(data.alert_mode == 1 ){
                            warningMsg += data.alert_msg ;
                        }

                        if(errorMsg != ''){
                            $rootScope.showAlert(errorMsg);
                        } else if(warningMsg != ''){
                            $rootScope.showConfirm(warningMsg, function(confirmDialog){
                                confirmDialog.hide();
                                if(callback){
                                    callback(data);
                                }
                            });
                        } else if(callback){
                            callback(data);
                        }
                    }
                });
            }

            // 輸入自動叫料數量
            function input_demand_qty(callback, feedback){
                $calculater.open(function(num, calcDialog){
                    if(+num == 0){
                        $rootScope.showAlert($filter('translate')('B0205.msg.demand_qty_must_gt_zero'));
                    }else{
                        calcDialog.hide();
                        if(callback)
                            callback((+num));
                    }
                },
                function(calcDialog){
                    calcDialog.hide();
                    $rootScope.showConfirm($filter('translate')('B0205.msg.is_skip_demand'), function(confirmDialog){
                        confirmDialog.hide();
                        if(feedback)
                            feedback();
                    }, function(confirmDialog){
                        confirmDialog.hide();
                        input_demand_qty(callback, feedback);
                    });
                },
                {
                    title : $filter('translate')('B0205.auto_demand_qty'),
                    defaultNum : 0,
                    decimal : true
                });
            }

            // 物料存量檢查作業
            function materialStockQtyCheck_Imp(plot_check_in, callback){
                // 開啟系統參數才需要確認物料存量
                if (feedingOpionOn){
                    materialStockQtyCheck(plot_check_in, function(){
                        if (callback)
                            callback();
                    });
                } else {
                    if (callback)
                        callback();
                }
            }

            // 確認是否自動叫料
            function checkAutoDemandImp(plot_check_in, index, checkList, callback){
                if(index < plot_check_in.length){
                    var plotItem = plot_check_in[index]; // 即將進站的批號
                    var checkItem = $filter('filter')(checkList, {plot_no: plotItem.plot_no}, true); //此批號待確認的物料
                    if(checkItem.length > 0){
                        checkAutoDemand(plotItem, checkItem[0], function(){
                            checkAutoDemandImp(plot_check_in, ++index, checkList, callback);
                        });
                    } else {
                        checkAutoDemandImp(plot_check_in, ++index, checkList, callback);
                    }
                } else {
                    if (callback)
                        callback();
                }
            }

            // 顯示是否自動叫料確認視窗
            function checkAutoDemand(plotItem, checkItem, callback){
                if(checkItem && checkItem.auto_demand_detail && checkItem.auto_demand_detail.length > 0){
                    var material = checkItem.auto_demand_detail.shift();

                    if(material.is_need_confirm == 'Y'){
                        $rootScope.showConfirm($filter('translate')('B0205.msg.is_need_auto_demand', {
                            plot_no: checkItem.plot_no,
                            material_no: material.material_no,
                            current_stock_qty: material.current_stock_qty,
                            min_stock_qty: material.min_stock_qty,
                            substitute_material_no: material.substitute_material_no
                        }),
                        function(confirmDialog){
                            input_demand_qty(function(qty){
                                plotItem.auto_demand_detail.push(creatMaterialDetail(material, 'Y', qty));
                                confirmDialog.hide();
                                checkAutoDemand(plotItem, checkItem, callback);
                            },
                            function(){
                                plotItem.auto_demand_detail.push(creatMaterialDetail(material, 'N', 0));
                                confirmDialog.hide();
                                checkAutoDemand(plotItem, checkItem, callback);
                            });
                        },
                        function(confirmDialog){
                            plotItem.auto_demand_detail.push(creatMaterialDetail(material, 'N', 0));
                            confirmDialog.hide();
                            checkAutoDemand(plotItem, checkItem, callback);
                        });
                    } else {
                        checkAutoDemand(plotItem, checkItem, callback);
                    }
                } else {
                    if(callback)
                        callback();
                }
            }

            // 建立自動叫料確認結果
            function creatMaterialDetail(material, is_auto, qty){
                var checkResult = {
                    material_no: material.material_no,
                    substitute_material_no: material.substitute_material_no,
                    position_no: material.position_no,
                    is_auto_demand: is_auto,
                    auto_demand_qty: qty,
                    put_in_place_type: material.put_in_place_type
                };
                return checkResult;
            }

            //物料存量檢查
            function materialStockQtyCheck(plot_check_in, callback){
                var content = {
                    plot_check_in: plot_check_in
                };
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.material_stock_qty_check_process',
                    content : content,
                    success : function(data){
                        if(data.check_result_detail && data.check_result_detail.length > 0){
                            checkAutoDemandImp(plot_check_in, 0, data.check_result_detail, function(){
                                if (callback)
                                    callback();
                            });
                        } else {
                            if (callback)
                                callback();
                        }
                    }
                });
            }

            //20220301 add by 翰鴻 for M#102396
            //验证插入处理
            function insertProductioninfData(dialog) {
                var content = {
                    plot_detail: [],
                    detail: dialog.plotSaveCollectInfo,
                    check_detail: [],
                    lot_no: dialog.plotInfo.plot_no,
                    op_no: dialog.plotInfo.op_no,
                    equipment_no: machine_no,
                    donoruser_no: dialog.account,
                    donor_remark: dialog.description,
                    qty: dialog.plotInfo.qty,
                    insert_flg: 'true'
                };
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.insert_productioninfdata',
                    content: content,
                    success: function (data) {
                    }
                });
            }

            //進站
            //20210519 Modify by德義家興for#90580
            function PlotCheckInProcess(options,dialog) {
                //20200807 add by linzh for SMMP机联网应用
                // machine_esi_check_in(machine_no, options.plotInfo, function () {
                AccLifeCheck(options.machine_no, options.plotInfo, function () {
                        //20210519 Modify by德義家興for#90580
                        var tempPCSNo = [];
                        // 20210524 modify by 德義_林佳諺 for #0086675 : 除錯(可能無dialog參數傳入而產生undefined錯誤)
                        if(dialog){
                            if(dialog.PCSNoList != undefined){
                                dialog.PCSNoList.forEach(function(item){
                                    tempPCSNo.push(item.pcs_no);
                                });
                            }
                        }
                        var istempPCSNo = false;
                        if (tempPCSNo.length > 0) {
                            istempPCSNo = true;
                        }

                        var content = {
                            plot_check_in: [{
                                //20210519 Modify by德義家興for#90580
                                got_pcs_no: istempPCSNo,
                                pcs_no: tempPCSNo,
                                collection_type: "0",

                                // 20220330 modify by chenshibo for#108636：取AP时间
                                report_datetime: options.plotInfo.sysdate_time,
                                machine_no: options.machine_no,
                                plot_no: options.plotInfo.plot_no,
                                op_seq: '',//
                                op_no: options.plotInfo.op_no,
                                workstation_no: '',//
                                product_no: options.plotInfo.product_no,
                                plot_stamp: options.plotInfo.plot_stamp,
                                qty: options.plotInfo.qty,
                                description: options.plotInfo.op_description,
                                auto_demand_detail: [], //物料明細
                                wait_detail: options.wait_detail,
                                op_plug_in_detail: options.op_plug_in_detail, // 爐批號資訊
                                fastening_info_detail: options.plotInfo.fastening_info_detail, // 扣件載具資訊
                                RequestFrom: "single",
                                NCFileName: options.plotInfo.NCFileName,
                                NCFileVersion: options.plotInfo.NCFileVersion
                            }]
                    };
                    if (options.IsInjectionMolding) {
                        var recipe_content = {
                            machine_no: options.machine_no,
                            lot_no: options.plotInfo.plot_no,
                            op_no: options.plotInfo.op_no,
                            pro_ver: options.recipe_list.product_no
                        };
                        recipe_check_info(recipe_content, function (data) {
                            // 20200225 modify by WeiTing for M#67346 - 注塑 - 如果 recipe_check 為 → false: 走原本的進站 ; true: 顯示檢核失敗頁面。 
                            if(!data.recipe_check){
                                fasteningCheck(options, function(){
                                    plot_check_in(content, options);
                                });
                            } else {
                                options.dialogB0205();
                                $mdDialog.serviceDialog('Inject01Service', options, function (options, dialogInject01) {
                                    dialogInject01.hide();
                                    fasteningCheck(options, function(){
                                        recipe_plot_check_in(content, options);
                                    })
                                });
                            };
                        });
                    }
                    else
                    {
                        fasteningCheck(options, function(){
                            plot_check_in(content, options);
                        });
                    }
                });
            }

            // 原本的進站送回服務
            function plot_check_in(content, options){
                materialStockQtyCheck_Imp(content.plot_check_in, function(){
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_WIP.plot_check_in_process',
                        content : content,
                        success: function (data, response) {
                            //20220225 add by 翰鴻 for M#102965
                            if (data.forceCheck)
                            {
                                $rootScope.showConfirm(response.Message, function (dialog) {
                                    dialog.hide();
                                    $mdDialog.serviceDialog('PasswordService', {
                                        mode: 'AreaLeader',
                                        equipmentno: options.machine_no,
                                        feedback: function () {
                                            content.isConfirm = true;
                                            plot_check_in(content, options);                                            
                                        }
                                    });
                                });                                
                            }
                            else
                            {
                                if (data.first_check_list && data.first_check_list.length > 0) {
                                    var str = data.first_check_list.join("<br>");
                                    $rootScope.showAlert(str);
                                }
                                else
                                    $rootScope.showToast(response.Message);

                                //进站成功后插入处理
                                //20210524 modify by 德義_林佳諺 for #0086675 : 判斷是否有insertdata物件
                                if (options.insertdata) {
                                    insertProductioninfData(options.insertdata);
                                }
                                if (options.feedback)
                                    options.feedback();
                            }                           
                        }
                    });
                });
            };

            // 20200225 modify by WeiTing for M#67346 - 注塑 - recipe檢核失敗頁面，強制進站改用此服務。
            function recipe_plot_check_in(content, options){
                materialStockQtyCheck_Imp(content.plot_check_in, function(){
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_INJECT.injection_recipe_plot_in_process',
                        content : content,
                        success : function(data, response){
                            $rootScope.showToast(response.Message);
                            if(options.feedback)
                                options.feedback();
                        }
                    });
                });
            };

            // 20200225 modify by WeiTing for M#67346 - 注塑 - recipe檢核。
            function recipe_check_info(content, callback){
                // var data = {
                //     recipe_check: true // true: 顯示檢核失敗頁面 ; false: 走原本邏輯直接進站
                // };
                // if(callback)
                //     callback(data);
                
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_INJECT.injection_recipe_check_info',
                    content : content,
                    success : function(data){
                        if(callback)
                            callback(data);
                    }
                });
            };

            function material_check_for_checkin_process(content, callback){
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.material_check_for_checkin_process',
                    content : content,
                    success : function(data){
                        if(data.warning_message && data.warning_message.length > 0) {
                            $rootScope.showConfirm(data.warning_message, function(confirmDialog){
                                confirmDialog.hide();
                                if(callback)
                                    callback();
                            });
                        } else {
                            if(callback)
                                callback();
                        }
                    }
                });
            };

            //扣件資訊檢查
            function fasteningCheck(options, callback){
                var msg = '', warring_msg = '';
                //依照need_vehicle判斷進站是否需要維護載具資訊?
                if(config.cache.sys_parameter['FasteningPackage'] == 1){
                    if(!options.plotInfo.fastening_info_detail.vehicle_name
                        || options.plotInfo.fastening_info_detail.vehicle_name == '' || !options.plotInfo.fastening_info_detail.vehicle_no){
                        if(options.plotInfo.fastening_info_detail.need_vehicle == 2){
                            //無維護載具編號，請問是否繼續執行
                            msg += $filter('translate')('B0206.msg.vehicle_info_empty');
                        } else if(options.plotInfo.fastening_info_detail.need_vehicle == 1){
                            //無維護載具編號，請先維護載具資訊
                            warring_msg += $filter('translate')('B0206.msg.vehicle_info_warning');
                        }
                    }
                }

                if(msg == ''){
                    if(warring_msg == ''){
                        callback();
                    } else {
                        $rootScope.showConfirm(warring_msg, function(confirm_dialog){
                            confirm_dialog.hide();
                            callback();
                        });
                    }
                } else {
                    $rootScope.showAlert(msg);
                }
            }

            //雙單位計算進站數量
            function CaculateFastening(fastening_info, qty){
                var _qty = $calculater.decimalMutiple($calculater.decimalSub(qty, fastening_info.vehicle_weight||0), (fastening_info.molecule||1)) / (fastening_info.denominator||1),
                    _accuracy = Math.pow(10, fastening_info.accuracy||0)||1;;
                if(fastening_info.conversion_rules == 0){
                    //無條件進位
                    _qty = Math.ceil(_qty * _accuracy) / _accuracy;
                } else if(fastening_info.conversion_rules == 1){
                    //無條件捨��?
                    _qty = Math.floor(_qty * _accuracy) / _accuracy;
                } else if(fastening_info.conversion_rules == 2){
                    //四捨五入
                    _qty = Math.round(_qty * _accuracy) / _accuracy;
                }
                return _qty;
            }

            //取得扣件資訊
            function fastening_info_get(plot_no, op_no, callback){
                if(config.cache.sys_parameter['FasteningPackage'] == '1'){
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_FAS.fastening_info_get',
                        content : {
                            plot_no:plot_no,
                            op_no:op_no,
                            action_type: '1' // 1(進站)、2(出站)
                        },
                        success : function(data){
                            if(data.defaultvehicle && data.defaultvehicle!=''){
                                vehicle_no_info_get(data.defaultvehicle, function(items){
                                    if(items && items.length > 0){
                                        data.vehicle_no = items[0].vehicle_no;
                                        data.vehicle_name = items[0].vehicle_name;
                                        data.vehicle_weight = items[0].vehicle_weight;
                                        data.vehicle_capacity = items[0].vehicle_capacity;
                                    }
                                    if(typeof(callback) == 'function'){
                                        callback(data);
                                    }
                                });
                            } else {
                                if(typeof(callback) == 'function'){
                                    callback(data);
                                }
                            }
                        }
                    });
                } else {
                    if(typeof(callback) == 'function'){
                        callback();
                    }
                }
            }

            //取得載具資訊
            function vehicle_no_info_get(vehicle_no, callback){
                var query_condition_info = [];
                if(vehicle_no && vehicle_no != '')
                    query_condition_info.push({column_name:'VehicleNo', query_mode:'0', value: vehicle_no, merge_condition_model:'AND'});
                $MMWService.pageNumberInfoGet({
                    form_name: 'PageNo_120',
                    query_condition_info:query_condition_info
                }, function(itemList){
                    if(callback)
                        callback(itemList);
                });
            }

            function NCCode_info_get(callback, lotno, opno, equipmentno) {
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.NCCode_info_get',
                    content: {
                        LotNO: lotno,
                        OPNO: opno,
                        EquipmentNO: equipmentno
                    },
                    success: function (data) {
                        if (callback)
                            callback(data);
                    }
                });
            }

            //20170511 modify by Dustdusk for 進站獨立成額外的function以利其他程式呼叫
            //20170810 modify by Dustdusk for 進站前需檢核治具生命週期
            service.SMES_PlotCheckInProcess = function(options){
                OpParameterInfo({
                    machine_no:options.machine_no,
                    is_line : options.type == 'line'?'1':'0',
                    lot_no : options.plotInfo.plot_no,
                    op_no : options.plotInfo.op_no,
                    area_no : options.area_no||''
                }, function(){
                    // 20240412 modify by wenwei for M#160539: 【湖南中钢】手动进站报工会校验人员报工权限，但是扫码进站不校验
                    var content = {
                        machine_no: machine_no,
                        plot_no: plot.plot_no,
                        op_seq: '',//
                        op_no: plot.op_no,
                        workstation_no: '',//
                        qty: '',
                        return_type: '1',
                        op_plug_in: plot.op_plug_in
                    };
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_WIP.plot_info_get',
                        content: content,
                        success: function (data) {
                            if (data.MsgLevel == 0) {
                                initPlotInfo(data, openDialog);
                            } else if (data.MsgLevel == 1) {
                                $rootScope.showConfirm(data.SysMsg, function (confirmDialog) {
                                    confirmDialog.hide();
                                    initPlotInfo(data, openDialog);
                                });
                            } else if (data.MsgLevel == 2) {
                                $rootScope.showAlert(data.SysMsg);
                            }
                            //M#91390 刷條碼時須考慮扣件
                            if(config.cache.sys_parameter['FasteningPackage'] === '1'){
                                fastening_info_get(options.plotInfo.plot_no, options.plotInfo.op_no, function(data){
                                    options.plotInfo.fastening_info_detail = data;
                                    PlotCheckInProcess(options);
                                });
                            }else{
                                PlotCheckInProcess(options);
                            }
                        }
                    });
                });
            };
            
            //回到進站畫面
            function backToTrackIn(dialog) {
                if (dialog.mode == 'lean-collect') {
                    dialog.plotCollectInfo = angular.merge([], production_inf_detail_backup);
                    production_inf_detail_backup = [];
                }
                dialog.mode = 'trackIn';
            }


            //生產信息收集檢查
            function productionInfValidate(production_inf_detail) {
                var msg = '';
                production_inf_detail.forEach(function (item) {
                    if (item.productioninf_value == undefined || item.productioninf_value == '') {
                        msg += $filter('translate')('B0206.msg.productioninf_value_empty', item) + '<br>';
                    }
                });
                return msg;
            }
        }]);
});
